<template>
  <div class="pagination" :class="className">
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="pagination.pageIndex"
      :page-sizes="pageSizeList"
      :page-size="pagination.pageSize"
      :layout="layout"
      :total="pagination.total"
      :prev-text="prevText"
      :next-text="nextText"
    >
    </el-pagination>
  </div>
</template>

<script>
export default {
  name: "zPagination",
  props: {
    // 自定义类型
    className: String,
    //点击页码后是否滚到顶端
    needToTop: { type: Boolean, default: true },
    // 分页组件
    layout: {
      type: String,
      default: "total, sizes, prev, pager, next, jumper",
    },
    // 分页配置
    pagination: {
      type: Object,
      default: () => {
        return { page_no: 1, page_size: 10, total: 0 };
      },
    },
    // 每页显示的条数
    pageSizeList: {
      type: Array,
      default: () => [5, 10, 15, 20],
    },
    //自定义上一页按钮
    prevText: String,
    //自定义下一页按钮
    nextText: String,
  },
  methods: {
    handleSizeChange(index) {
      this.pagination.pageIndex = 1;
      const pagination = Object.assign(
        { ...this.pagination },
        { pageSize: index }
      );
      this.$emit("handle-page-change", pagination);
      this.needToTop && this.backToTop();
    },
    handleCurrentChange(index) {
      const pagination = Object.assign(
        { ...this.pagination },
        { pageIndex: index }
      );
      this.$emit("handle-page-change", pagination);
      this.needToTop && this.backToTop();
    },
    // 回到顶部
    backToTop() {
      const start = window.pageYOffset;
      let i = 0;
      this.interval = setInterval(() => {
        const next = Math.floor(this.easeInOutQuad(10 * i, start, -start, 500));
        if (next <= 0) {
          window.scrollTo(0, 0);
          clearInterval(this.interval);
        } else {
          window.scrollTo(0, next);
        }
        i++;
      }, 16);
    },
    easeInOutQuad(t, b, c, d) {
      if ((t /= d / 2) < 1) return (c / 2) * t * t + b;
      return (-c / 2) * (--t * (t - 2) - 1) + b;
    },
  },
};
</script>

<style lang="less" scoped>
.pagination {
  margin: 10px;
}
</style>
